import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import { ElMessage } from 'element-plus'

import { staticRoutes } from "@/router/routes";
//类型
import type { requestUserInfoReturnType, requestParamType } from '@/api/userLogin'
import type { RouteRecordRaw } from "vue-router";

//方法
import { requestLogin, requestUserInfo, requestLoginOut } from "@/api/userLogin"


//当前userInfo的小仓库的state类型限制
export interface UserInfoState {
  token: string;
  //userInfo的值是请求回来的,所以类型直接设置为请求的返回值类型
  userInfo: requestUserInfoReturnType;
  menuRoutes: RouteRecordRaw[];
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: (getToken() as string) || "",
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    //把静态路由表保存起来,侧边栏其实是拿到这个路由表,然后遍历生成侧边栏元素的
    menuRoutes: staticRoutes,
  }),

  actions: {
    async login(loginParam: requestParamType) {
      try {
        const result = await requestLogin(loginParam)
        this.token = result.token
        //自动登录
        setToken(this.token)
      } catch (e) {
        //如果将来调用这个login方法时,请求出现问题，则返回一个失败的promise实例，在哪调用的这个login 再哪里处理
        // this.reset();
        return Promise.reject(e)
      }
    },

    async getInfo() {
      try {
        //发送用户信息请求
        const result = await requestUserInfo()
        //把数据交给state
        this.userInfo = result;
      } catch (e) {
        /* token过期设置为空 */
        this.token = ''
        Promise.reject(e)
      }
    },

    async loginOut() {
      try {
        await requestLoginOut()
        //作出清理工作
        this.reset();
      } catch (e) {
        return Promise.reject(e)
      }
    },
    reset() {
      // 删除local中保存的token
      removeToken()
      /// 恢复原始的state的空值
      this.token = ''
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: "",
        avatar: "",
      }
    },
  },
});
